package com.mar.meclient.bt.ui.impl;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Display;

import com.mar.meclient.util.ui.IPage;
import com.mar.meclient.util.ui.IPageNavigator;


/**
 * TODO: implement
 * @author mar
 *
 */
public class BTPageNavigator implements IPageNavigator {

	private final Display display;
	
	private final BTInquiryUI btDeviceInquiryPage;
	
	private IPage currentPage;// for debug so far
	
	public BTPageNavigator(Display disp) {
		this.display = disp;
		
		this.btDeviceInquiryPage = new BTInquiryUI(this);
	}
	
	public void showStartPage(){
		if ( btDeviceInquiryPage.getDesplayable() != null ){
			throw new IllegalStateException("showStartPage could be called only once!");
		}
		btDeviceInquiryPage.createPageContent(null);
		setCurrentPage(btDeviceInquiryPage);
	}
	
	public void navigateBack(IPage from) {
		if ( from instanceof BTInquiryUI ){
			//TODO: implement exit
			return;
		}
		if ( from instanceof BTMainPage ){
			// open inquiry page with old content
			setCurrentPage(btDeviceInquiryPage);
			return;
		}

	}

	public void navigateNext(IPage from, Object pageResult) {
		if ( from instanceof BTInquiryUI ){
			IPage mainBtPage = new BTMainPage();
			mainBtPage.createPageContent(pageResult);// pass result from inquiry page as input 
			setCurrentPage(mainBtPage);
		}
	}

	public void navigateOnCriticalException(IPage page, Exception e) {
		Alert alert = new Alert("Exception", e.getMessage(), null, AlertType.WARNING);
//        alert.setTimeout(Alert.FOREVER);
		display.setCurrent(alert, getStartPage().getDesplayable());
	}

	public void showPageProblem(IPage page, String message, Exception e) {
		Alert alert = new Alert("Exception", e.getMessage(), null, AlertType.WARNING);
//        alert.setTimeout(Alert.FOREVER);
		display.setCurrent(alert, page.getDesplayable());
	}
	
	// ----------- IMPL SECTION --------------//
	
	protected IPage getStartPage(){
		return btDeviceInquiryPage;
	}
	
	protected void setCurrentPage(IPage page){
		display.setCurrent(page.getDesplayable());
		this.currentPage = page;
	}
}
